package com.attilax.wrmi;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.reflect.ConstructorUtils;
import org.apache.commons.lang3.reflect.MethodUtils;









//import com.attilaax.encode.EncodeX;   sould recomm q229 ati
//import com.attilax.core;
import com.attilax.exception.ExUtil;
import com.attilax.ioc.IocUtilV2;
import com.attilax.ioc.IocXq214;
 
import com.attilax.json.AtiJson;
import com.attilax.lang.Global;
import com.attilax.lang.ParamX;
import com.attilax.ref.refx;
import com.attilax.web.ReqX;
import com.google.common.collect.Maps;


/**
 * $method=com.attilax.jsna.test.add
 * @author Administrator
 *
 */
public class Wrmi {

	/**
	 * def output raw type ..if list map object use json fmt
	 * 
	 * @param req
	 * @return
	 */
	@SuppressWarnings("all")
	public String exe(Map m) {
//		Map m=Maps.newLinkedHashMap();
//		if(req2 instanceof String)  //cs envi 
//		  m = new ParamX().urlParams2Map((String) req2);
//		 
		 
	
	 
		Object[] params_objArr = getParamsArr(m);
		String meth =getMethod(m);
		String classname = refx.getClassName(meth);
		String meth_name = refx.getMethodName(meth);
	 

		Object o;

		try {
			// String apptype=System.getProperty("apptype");			
			o =  IocUtilV2.getBean(classname);
			Object invokeMethod_ret = com.attilax.reflect.MethodUtils.invokeMethod(o, meth_name,
					params_objArr);
			String ret = "";
			if (invokeMethod_ret instanceof String)
				ret = (String) invokeMethod_ret;
			else if (invokeMethod_ret instanceof Integer || invokeMethod_ret instanceof Double)
				ret =  invokeMethod_ret.toString();
			else
				ret =AtiJson.toJson(invokeMethod_ret);

			return ret;
		//q31   good ex throw 
		}catch(InvocationTargetException ite)
		{
		//	ExUtil.throwEx(ite.getCause());
			return  AtiJson.toJson(ite.getCause());
		} catch (Throwable e) {
			e.printStackTrace();
			return  AtiJson.toJson(e);

		}

	}

	/**
	attilax    2016年4月19日  下午5:49:16
	 * @param m
	 * @return
	 */
	private String getMethod(Map m) {
		String s= (String) m.get("$method"); 
		if(s==null)
			s= (String) m.get("$m"); 
			
				if(s==null)
			s= (String) m.get("method"); 
		return s;
	}

	private Object[] getParamsArr(Map m) {
		List paras_li = new ArrayList();
		//m.get("param")
		if (m.get("param") != null)
			paras_li.add(convertReqObjParams( m.get("param")));
		for (int i = 0; i < 7; i++) {
			String param_index = "param" + String.valueOf(i);
			if (m.get(param_index) != null)
				paras_li.add(convertReqObjParams(m.get(param_index)));

		}
		Object[] params_objArr = paras_li.toArray();
		return params_objArr;
	}

	private Object convertReqObjParams(Object object) {
		if(object.toString().trim().equals("$req"))
			return Global.req.get();
		if(object.toString().trim().equals("$null"))
			return null;
		return object;
	}

 

}
